<?php
/**
 * CreateTime: 2023/7/14 14:29
 */

namespace App\Http\Controllers\Customer;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\Role\RoleConsts;
use App\Func\AdminTokenFunc;
use App\Func\EncryptionFunc;
use App\Func\ResponseFunc;
use App\Http\Requests\Customer\CustomerAdminCreatedRequest;
use App\Http\Requests\ListBasicRequest;
use App\Models\Auth\AuthBasicModel;
use App\Models\Auth\AuthRoleModel;
use App\Models\Auth\RoleModel;
use App\Models\Company\CompanyModel;
use App\Models\Customer\CustomerModel;
use App\Models\Department\DepartmentModel;
use App\Models\Staff\StaffDepartmentModel;
use App\Models\Staff\StaffModel;
use App\Models\Staff\StaffRoleModel;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Rfc4122\UuidV4;

class CustomerController
{

    public function addCustomerByAdminCreated(CustomerAdminCreatedRequest $request){
        $data = $request->all();
        $cm = new CustomerModel();
        $adminTokenInfo = new AdminTokenFunc();
        // 创建客户
        $staffModel = new StaffModel();
        $uuidV4 = UuidV4::uuid4()->toString();
        // 设置默认值
        $data['customer_uuid'] = $uuidV4;
        $data['customer_status'] = 1;
        $data['status'] = 1;
        // 创建客户端登录账号
        try {
            DB::beginTransaction();
            // 校验当前客户是否存在
            $isExists = $staffModel->isExistByCondition([
               'staff_login_account' => $data['customer_account']
            ]);
            if($isExists){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '当前客户账号已存在',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }

            $data['owner_id'] =$adminTokenInfo->getUkTInfo()['admin_id'];
            $data['staff_admin_account'] = $data['customer_account'];

            // 创建一个公司
            $companyModel = new CompanyModel();
            $companyId = $companyModel->add([
                'company_name' => $data['customer_name'],
                'company_level' => 1,
                'company_parent_id' => 0,
                'status' => 1
            ],true);

            // 创建一个部门
            $departModel = new DepartmentModel();
            $departmentId = $departModel->add([
                'company_id' => $companyId,
                'department_name' => "开发部",
                'department_level' => 1,
                'status' =>1
            ],true);



            $data['company_id'] = $companyId;
            $customerId = $cm->add($data);

            // 生成 RSA 密钥对
            $privateKey = openssl_pkey_new([
                'private_key_bits' => 2048, // 密钥位数
                'private_key_type' => OPENSSL_KEYTYPE_RSA, // 密钥类型
            ]);

            // 提取私钥
            openssl_pkey_export($privateKey, $privateKeyString);

            // 提取公钥
            $publicKey = openssl_pkey_get_details($privateKey)['key'];

            $addStaffData = [
                'company_id' => $companyId,
                'staff_name' => $data['customer_name']."管理员",
                'staff_status' => 1,#启用
                'staff_phone_number' => $data['customer_phone'],
                'staff_login_account' => $data['staff_admin_account'],
                'staff_login_password' => EncryptionFunc::encryptionHash($data['customer_login_password']),
                'staff_type' => 2,
                'union_id' => UuidV4::uuid4()->toString(),
                'pu_key' => $publicKey ,
                'pv_key' => $privateKeyString
            ];
            $staffId = $staffModel->add($addStaffData,true);


            // 绑定当前用户和部门
            $deptStaffModel = new StaffDepartmentModel();
            $deptStaffModel->add([
                'staff_id' => $staffId,
                'department_id' => $departmentId,
            ],true);

            // 更新客户表
            $cm->where('customer_id',$customerId)
                ->update([
                'staff_id' => $staffId
            ]);

            // 为当前公司创建权限
            $roleModel = new RoleModel();
            $authRoleModel = new AuthRoleModel();
            $authModel = new AuthBasicModel();

            // 把当前角色绑定所有管理员权限
            $roleId = $roleModel->addRoleNotAuth([
                'role_name' => '管理员',
                'company_id' => $companyId,
                'status' => 1,
                'role_code' => RoleConsts::ROLE_TYPE_ADMIN
            ]);
            // 允许通过的权限 auth_category
            $auth_category = [
                'auth_menu',
                'admin',
                'staff'
            ];
            // 设置默认权限
            $authList = $authModel->select([
                'auth_id'
            ])->withoutGlobalScopes()
            ->where('company_id',66)
            ->whereIn('auth_category',$auth_category)
            ->get()
            ->toArray();
            foreach($authList as $value){
                $authRoleModel->addRoleAuthByRoleNotAuth([
                    'auth_id' => $value['auth_id'],
                    'role_id' => $roleId,
                    'auth_value' => 1,
                    'status' => 1,
                    'company_id' => $companyId
                ]);
            }
            // 绑定角色和用户
            $staffRollModel = new StaffRoleModel();
            $staffRollModel->add([
                'staff_id' => $staffId,
                'role_id' => $roleId
            ],true);
            // 新增调解员角色
            $roleIdTjy = $roleModel->addRoleNotAuth([
                'role_name' => '调解员',
                'company_id' => $companyId,
                'status' => 1,
                'role_code' => RoleConsts::ROLE_TYPE_TJY
            ]);
            $auth_categoryTjy = [
                'staff'
            ];
            // 设置默认权限
            $authListTjy = $authModel->select([
                'auth_id'
            ])->withoutGlobalScopes()
                ->where('company_id',66)
                ->whereIn('auth_category',$auth_categoryTjy)
                ->get()
                ->toArray();
            foreach($authListTjy as $value){
                $authRoleModel->addRoleAuthByRoleNotAuth([
                    'auth_id' => $value['auth_id'],
                    'role_id' => $roleIdTjy,
                    'auth_value' => 1,
                    'status' => 1,
                    'company_id' => $companyId
                ]);
            }
            $staffRollModel->add([
                'staff_id' => $staffId,
                'role_id' => $roleIdTjy
            ],true);

            DB::commit();
            return ResponseFunc::returnJson(
                'ok',
                null,
                '新增客户成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            DB::rollBack();
            return ResponseFunc::returnJson(
                'error',
                null,
                '新增客户失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }


    }

    public function getCustomerList(ListBasicRequest $request){
        $pageSize = $request->get('page_size');
        $filters = $request->get('filters');
        $cm = new CustomerModel();
        $query = $cm->select([
            'customer_id',
            'customer_name',
            'customer_type',
            'customer_phone',
            'customer_uuid',
            'staff_admin_account',
        ]);
        if($filters){
            if(isset($filters['customer_type']) && $filters['customer_type']){
                $query = $query->where('customer_basic.customer_type',$filters['customer_type']);
            }
            if(isset($filters['customer_name']) && $filters['customer_name']){
                $query = $query->where('customer_basic.customer_name','LIKE',"%".$filters['customer_name']."%");
            }
            if(isset($filters['customer_phone']) && $filters['customer_phone']){
                $query = $query->where('customer_basic.customer_phone','LIKE',"%".$filters['customer_phone']."%");
            }
        }
        $data = $query->where('customer_basic.status',BaseConsts::STATUS_NORMAL)
                ->orderBy('customer_basic.customer_id','desc')
                ->Paginate($pageSize)->toArray() ?? [];
        return ResponseFunc::returnJson(
            'ok',
            $data,
            '获取客户列表成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function editCustomerInfo($customerId){
        $cm = new CustomerModel();
        try {
            $data = request()->all();
            if(isset($data['customer_login_password'])){
                $data['customer_login_password'] = EncryptionFunc::encryptionHash($data['customer_login_password']);
            }
            unset($data['created_time']);
            unset($data['updated_time']);
            unset($data['last_login_time']);
            unset($data['staff_admin_account']);
            unset($data['staff_id']);
            unset($data['customer_uuid']);
            unset($data['customer_status']);
            unset($data['owner_id']);
            unset($data['status']);
            $cm->where(
                'customer_id',$customerId
            )->update($data);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '编辑客户成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '编辑客户失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getCustomerInfo($customerId){
        $cm = new CustomerModel();
        $cmInfo = $cm->select([
            'customer_name',
            'customer_type',
            'customer_phone',
            'customer_uuid',
            'staff_admin_account'
        ])->where('customer_id',$customerId)
            ->where('status',1)->first();
        return ResponseFunc::returnJson(
            'ok',
            $cmInfo,
            '获取客户列表成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function resetCustomerBindStaffPassword($customerId){
        $cm = new CustomerModel();
        $data = request()->all();
        if(!isset($data['staff_login_password'])){
            return ResponseFunc::returnJson(
                'error',
                null,
                '密码不能为空',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        // 获取绑定信息
        $cmInfo = $cm->select([
            'staff_id'
        ])->where('customer_id',$customerId)->first();
        if(!isset($cmInfo['staff_id'])){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前绑定用户错误',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        $data['staff_login_password'] = EncryptionFunc::encryptionHash($data['staff_login_password']);
        $staffModel = new StaffModel();
        try {
            $staffModel->where('staff_id',$cmInfo['staff_id'])->update([
                'staff_login_password' => $data['staff_login_password']
            ]);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '重置用户密码成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '重置用户密码失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }


    }


}